package com.xwh.b2c.interceptors;

import com.xwh.b2c.exceptions.BusinessException;
import com.xwh.b2c.handlers.BaseContextHandler;
import com.xwh.b2c.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component//交给springboot管理

//拦截器：1.交给springboot管理 2.实现拦截器方法(preHandle) 3.注册拦截器(webConfig)

//拦截器  拦截token里面的id
public class AuthorizationInterceptor implements HandlerInterceptor {
    //注意：如果是登录的话，没有token 一样会被拦截 出现矛盾 所以在webConfig中 要放行login



    //注入JWT工具类 用来解析token
    @Resource
    private JwtUtil jwtUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器生效了..........");
        String token = request.getHeader("Authorization");//header中token参数名
        log.info("token:{}", token);


        /*
         * URL: https:// localhost:8080/b2c/login
         * URI: b2c/login
         * 使用request查看需要放行的路径
         * */
        String uri = request.getRequestURI();
        log.info("uri:{}",uri);
        if (token == null || token.equals("")) {
            throw new BusinessException("token为空");
        }

        //解析token
        //{code: -1, msg: "Illegal base64url character: ' '", data: null, status: -1}
        //生成的token长这样：Bearer eyJhbGciOiJIUzI1NiJ9.eyJpZCI6MSwiaWF0IjoxNzUxOTY0ODU4LCJleHAiOjE3NTE5NjUyMTh9.Bsy6N1fnyEFBOe_Wl11ap8fSWNdH5fl5S_r83tUnOgo
        //需要将Bearer替换为空
        token=token.replace("Bearer ","");

        Claims claims = jwtUtil.parseToken(token);
        Long id = claims.get("id", Long.class);
        log.info("id:{}", id);

        /*
        * 获得了id 但是id如何传递到Service?
        * ***使用线程变量***
        * 请求开始到请求结束的任何时候都可以获取到线程变量
        * 实现BaseContextHandler
        *
        * */
        BaseContextHandler.set(id);
        return true;
    }
}
